package com.goliathonline.android.kegbot;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

public class Background extends Service
{
	private Connector _conn;
	private SharedPreferences _prefs;
	private String _host;
	private int _port;
	private boolean _isServiceStarted = false;
	private static final String FLOW_UPDATE = "com.goliathonline.android.kegbot.flow_update";
	
	@Override
	public void onCreate()
	{
		super.onCreate();
		//Get the xml/preferences.xml preferences
		_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		_host = _prefs.getString("hostPref", "kegbot");
		_port = Integer.parseInt(_prefs.getString("port", "9805"));
		Log.d("Kegbot Background","Service Created");
	}
	
	@Override
	public void onStart(Intent intent, int startId)
	{
		super.onStart(intent, startId);
		try{
			_conn = new Connector(_host, _port);
			Listen();
			_isServiceStarted = true;
			Log.d("Kegbot Background","Service Started");
		}catch(Exception e) {
			Log.d("Kegbot Background","Error starting service: " + e.toString());
		}
		
		
		// TODO: Actions to perform when service is started.
	}
	
	@Override
	public void onDestroy()
	{
		_conn.Disconnect();
		_isServiceStarted = false;
		Log.d("Kegbot Background","Service destroy");
		super.onDestroy();
	}
	
	@Override
	public IBinder onBind(Intent intent)
	{
		// TODO: Replace with service binding implementation.
		return null;
	}
	
	private void Listen()
	{
		Intent intent = new Intent(FLOW_UPDATE);
		String message;
		while(_conn.IsConnected() && _isServiceStarted)
		{
			Log.d("Kegbot Background","Listen Loop");
			message = _conn.Listen();
			if (message != "error")
			{
				intent.putExtra("message", message);
				Log.d("Kegbot Background","Broadcast: " + message);
				sendBroadcast(intent);
			}
		}
	}
}
